package com.mdxl.shiro.util;

import com.mdxl.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @Author:MuJiuTian
 * @Description: shiro工具类
 * @Date: Created in 下午4:49 2019/11/5
 */
public class ShiroUtils {

    /**
     * 算法加密类型
     */
    public final static String hashAlgorithmName_SHA = "SHA-256";
    public final static String hashAlgorithmName_MD5 = "MD5";

    /**
     * type true：则使用MD5加密、 false：则使用SHA-256加密
     * password 登陆密码
     * salt 盐值
     * hashIterations 循环次数，如果是2，则为MD5(MD5(password))
     */
    public static String encryption(String password, String salt,int hashIterations,boolean type) {
        if (type) {
            return new SimpleHash(hashAlgorithmName_MD5, password, salt, hashIterations).toString();
        } else {
            return new SimpleHash(hashAlgorithmName_SHA, password, salt, hashIterations).toString();
        }
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static User getUserEntity() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }

    public static int getUserId() {
        return getUserEntity().getId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * 是否拥有该权限
     * @param permission 权限标识
     * @return true：是  false：否
     */
    public boolean hasPermission(String permission) {
        Subject subject = SecurityUtils.getSubject();
        return subject != null && subject.isPermitted(permission);
    }
}
